<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\User;
use fast\Random;
use GuzzleHttp\Client;
use think\Collection;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 家长
 *
 * Class Parent
 * @package app\admin\controller
 */
class Parents extends Backend
{
    protected $relationSearch = true;
    /**
     * @var \app\common\model\Parents
     */
    protected $model = null;
    protected $searchFields = 'id,name';
    protected $noNeedRight = ['searchlist'];
    protected $schoolLimit = true;
    protected $modelValidate = true;
    protected $modelSceneValidate = true;
    protected $genderData = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Parents');

        $this->genderData =  User::getGenderList();
        $this->view->assign('genderData', $this->genderData);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->alias('parents')
                ->with('school')
                ->with('user')
                ->where($where)
                ->count();

            $list = $this->model
                ->alias('parents')
                ->with('school')
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $parents_params = $this->request->post("row/a");
            $user_params = $this->request->post("user/a");
            if ($parents_params && $user_params) {

                if ($this->schoolLimit && $this->schoolLimitFieldAutoFill) {
                    $parents_params[$this->schoolLimitField] = $this->auth->school_id;
                }

                $result = false;
                Db::startTrans();
                try {

                    $user = \app\common\model\User::getUser($user_params['mobile'], $user_params['nickname'], ['school_id' => $this->auth->school_id]);
                    if (isset($user['error'])) {
                        $this->error($user['error']);
                    }

                    $count = $this->model->where('user_id', $user->id)->count();
                    if ($count) {
                        $this->error('家长已存在');
                    }

                    $parents_params['user_id'] = $user->id;
                    $result = $this->model->allowField(true)->save($parents_params);


                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout' => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/user/add', [
                        'form_params' => [
                            'id' => $user->id,
                            'name' => $user_params['nickname'],
                            'gender' => $user_params['gender'],
                            'mobile' => $user_params['mobile'],
                            'role' => 2,
                        ]
                    ]);
                    $status = $response->getStatusCode();

                    if (!$result) {
                        Db::rollback();
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->alias('parents')->with('user')->where('parents.id', $ids)->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $parents_params = $this->request->post("row/a");
            $user_params = $this->request->post("user/a");
            if ($parents_params) {

                if ($user_params) {
                    $validate = Validate('User');
                    $res = $validate->scene('edit')->check($user_params);
                    if (!$res) {
                        $this->error($validate->getError());
                    }
                }

                $result = false;
                Db::startTrans();
                try {

                    if ($user_params) {
                        $user_params['username'] = $user_params['mobile'];
                        User::where('id', $row->user->id)->update($user_params);
                    }

                    $result = $row->allowField(true)->save($parents_params);

                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout' => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/user/edit', [
                        'form_params' => [
                            'id' => $row->user->id,
                            'name' => $user_params['nickname'],
                            'gender' => $user_params['gender'],
                            'mobile' => $user_params['mobile'],
                            'role' => 2,
                        ]
                    ]);
                    $status = $response->getStatusCode();

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $schoolIds = $this->getDataLimitSchoolIds();
            if (is_array($schoolIds)) {
                $this->model->where($this->schoolLimitField, 'in', $schoolIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            Db::startTrans();
            try {
                $delete_ids = array_column($list, $pk);
                $delete_user_ids = array_column($list, 'user_id');

                $this->model->whereIn('id', $delete_ids)->delete();
                User::whereIn('id', $delete_user_ids)->delete();

                $client = new Client([
                    'base_uri' => config('suzhi.url'),
                    'timeout' => 30,
                    'allow_redirects' => true
                ]);
                $response = $client->request('POST', '/platform/user/del', [
                    'form_params' => [
                        'ids' => $delete_user_ids,
                    ]
                ]);
                $status = $response->getStatusCode();

                Db::commit();

                $this->success();

            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
